<?php

namespace App\Model;

use EasySwoole\ORM\AbstractModel;

/**
 * Class ConsumeOrderModel
 * Create With Automatic Generator
 * @property $id
 * @property $user_id
 * @property $info
 * @property $origin_money
 * @property $consume_money
 * @property $offer_money
 * @property $create_time
 */
class ConsumeOrderModel extends AbstractModel
{
    protected $tableName = 'bee_consume_order001';

    protected $primaryKey = 'id';

    protected $autoTimeStamp = true;
    protected $createTime = 'create_time';
    protected $updateTime = false;

    /**
     * 设置分表名
     * @param int $userId
     * @return ConsumeOrderModel|string
     * @throws \EasySwoole\ORM\Exception\Exception
     */
    public function changeTableName(int $userId = 1)
    {
        $mod = $userId % 100;
        $trueTableName = 'bee_consume_order' . str_pad($mod, 3, "0", STR_PAD_LEFT);
        return $this->tableName($trueTableName);
    }


    /**
     * 添加消费订单
     * @param int $userId
     * @param float $money
     * @param float $offerMoney
     * @param string $message
     * @return bool|int
     * @throws \EasySwoole\ORM\Exception\Exception
     * @throws \Throwable
     */
    public function add(int $userId, float $money, float $offerMoney, string $message)
    {
        return $this->changeTableName($userId)->data([
            'user_id' => $userId,
            'info' => $message,
            'origin_money' => $money,
            'consume_money' => floatval($money - $offerMoney),
            'offer_money' => $offerMoney,
            'create_time' => time(),
        ], false)->save();
    }
}